package core;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import model.Member;

import org.jboss.annotation.ejb.LocalBinding;

import utils.Utils;

@Stateless
@LocalBinding(jndiBinding="local/MemberManager")
public class MemberManager implements MemberManagerLocal{

    @PersistenceContext
    private EntityManager em;
    
	@Override
	public Member findOrCreateMember(String memberCellphone,
			String memberEmail, String memberPassword) {
		
		Member member = findMember(memberCellphone, memberEmail);

		if(member == null){
			member = new Member();
			member.setCellphone(memberCellphone);
			member.setEmail(memberEmail);
			member.setPassword(memberPassword);
			em.persist(member);
		}else if (!member.getPassword().equals(memberPassword)){
			member = null;
		}
		
		return member;
	}
	
	@Override
	public Member findOrCreateMember(String memberCellphone,
			String memberEmail) {
		
		Member member = findMember(memberCellphone, memberEmail);

		if(member == null){
			member = new Member();
			member.setCellphone(memberCellphone);
			member.setEmail(memberEmail);
			
			em.persist(member);
		}
		
		return member;
	}
	

	@Override
	public Member loginMember(String memberCellphone,String memberEmail, String memberPassword) {
		
		Member member = findMember(memberCellphone, memberEmail);

		if(member != null && !member.getPassword().equals(memberPassword)){
			member = null;
		}
		
		return member;
	}
	
	public Member findMember(String memberCellphone, String memberEmail) {
		List resultList;
		Member member = null;
		if(Utils.isEmpty(memberEmail)){
			 resultList = em.createQuery("select m from Member m where m.cellphone = :cellphone").setParameter("cellphone", memberCellphone).getResultList();	
		}else{
			resultList = em.createQuery("select m from Member m where m.email = :email").setParameter("email", memberEmail).getResultList();
		}
		
		if(resultList.size() == 1){
			member = (Member) resultList.get(0);
		}
		
		return member;
	}

}
